import store from '@/store'
import Cookies from 'js-cookie'
import router from '@/components/storybook/router'
import qs from 'qs'
import { apiInterface } from '@/api'
import { clearLoginInfo, rememberRoute } from '@/utils'
import { isPlainObject, cloneDeep,get } from 'lodash'
import { createAxios } from '@/components/storybook/utilties/axios'
import { InterceptContext } from '@/components/storybook/s-Intercept/intercept-context'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'

const requestInterceptors = (config, options) => {
  config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  if (!(config.data &&config.data.formCode &&config.data.formCode === '1536969662384967680')) {
    config.headers['token'] = Cookies.get('token') || ''
    config.headers['tenantCode'] = Cookies.get('tenant_code') || ''
  }
  config.headers['loginAsRoleId'] = sessionStorage.getItem('loginAsRoleId')
    ? sessionStorage.getItem('loginAsRoleId')
    : ''
  config.headers['loginAsUserId'] = sessionStorage.getItem('loginAsUserId')
    ? sessionStorage.getItem('loginAsUserId')
    : ''
  config.headers['timezoneOffset'] =  store.state.user.timezoneOffset
    ? store.state.user.timezoneOffset
    : ''
  config.headers['timezoneId'] = store.state.user.timezoneId
    ? store.state.user.timezoneId
    : ''
  if(config.url.includes('/apigateway/api/dataset/1640894768406925313')){ 
    config.headers['apiKey'] = '4a97d6080db646e0aaa6f9acbb1e4b39'
  }
  config.headers['groupMergeFlag'] = store.state.system.groupMergeFlag
  var defaults = {}
  try {
    if (
      window.location.pathname.includes('/publicReport') ||
      window.location.pathname.includes('/publicReportPdf')
    ) {
      // if (config.method === 'get') {
        const resourceId = sessionStorage.getItem('resourceId')
        if (config.params) {
          if (getQueryString('pageid') || resourceId) {
            config.params.public = getQueryString('pageid') || resourceId
          } else {
            config.params.shareToken = getQueryString('shareToken')
          }
        } else {
          config.params = {}
          if (getQueryString('pageid') || resourceId) {
            config.params.public = getQueryString('pageid') || resourceId
          } else {
            config.params.shareToken = getQueryString('shareToken')
          }
        }
      if (window.location.pathname === '/publicReportPdf') {
        config.params.noValid = true
      }
      // }
    }
  } catch (error) {}
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      ...{
        _t: new Date().getTime()
      }
    }
  }
  config.params = {
    ...config.params
    // queryType: store.state.REFRESHCACHE ? 'REFRESHCACHE' : null
  }

  if (isPlainObject(config.params)) {
    config.params = {
      ...defaults,
      ...config.params
    }
  }
  if (isPlainObject(config.data)) {
    config.data = {
      ...defaults,
      ...config.data
    }
    if (
      /^application\/x-www-form-urlencoded/.test(config.headers['content-type'])
    ) {
      config.data = qs.stringify(config.data)
    }
  }
  return config
}

const responseInterceptors = response => {
  if (response.data.code !== 0) {
    var params = {
      tenantCode: store.state.user.tenantCode,
      username: store.state.user.username.split('@')[0],
      company: store.state.user.tenantName,
      errorInfo: response.data.msg,
      errorType: location.pathname,
      errorCode: response.data.code,
      httpStatusCode: response.status,
      url: response.config.url,
      email: store.state.user.email
    }
    if (
      !response.config.url.includes('/save-mq') &&
      !response.config.url.includes('/error') &&
      !response.config.url.includes('login')
    ) {
      postError(params)
    }
  }
  // store.commit('SET_API_LOAD_STATUS', false)
  if (response.data.code === 401 || response.data.code === 10001) {
    const tempRouter = store.state.contentTabs
    clearLoginInfo()
    rememberRoute(tempRouter)
    if (
      window.location.pathname !== '/login' &&
      window.location.pathname !== '/loginAsAccount' &&
      window.location.pathname !== '/emaillogin'
    ) {
      if (!store.state.app.beforeLoginPage)
        store.state.app.beforeLoginPage = window.location.pathname
      if (!store.state.app.beforeLoginParams)
        store.state.app.beforeLoginParams = window.location.search
    }
    store.state.app.isNavToLogin = true
    if (
      window.location.href.includes('portalDashboard') ||
      window.location.href.includes('portalPageDashboard') ||
      window.location.href.includes('loginAsAccount') ||
      window.location.href.includes('portal')
    ) {
      router.replace({
        name: 'loginAsAccount'
      })
    } else {
      const search = window.location.href.split('?')[1]
        ? window.location.href.split('?')[1].split('&')[0]
        : null

      router.replace({
        path: search
          ? `/${store.state.system.loginRouter}?${encodeURIComponent(
              search
            )}`
          : store.state.system.loginRouter
      })
    }
    response.data.code !== 401 && useErrorMessage(response.data.msg);
    return Promise.reject(response.data.msg)
  }

  try {
    if (response.config.url === 'web/reports/sys/model/sql') {
      if (
        response.data &&
        response.data.code === 0 &&
        response.data.data &&
        response.data.data.length > 0
      ) {
        response.data.data.forEach(item => {
          for (var key in item) {
            let result = null
            result = response.data.selectFields.find(i => i.bind === key)            
            if (result && result.dbType && result.dbType === 'number') {
              // if (!item[key]) {
              //   item[key] = 0
              // }
            }
          }
        })
      }

      if (
        response.data &&
        response.data.code === 0 &&
        response.data.selectFields &&
        response.data.selectFields.length > 0
      ) {
        // if (response.data.selectFields.length > 0) {
        response.data.selectFields.forEach(item => {
          // if (item.businessType === 'datetime' && !item.fieldsFormat) {
          //   item.fieldsFormat = 'YYYY-MM-DD HH:mm'
          // } else if (item.businessType === 'date' && !item.fieldsFormat) {
          //   item.fieldsFormat = 'YYYY-MM-DD'
          // }
          if (
            item.businessType === 'number' &&
            !item.fieldsFormat &&
            !item.fieldsNewFormat
          ) {
            item.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 0,
              option: ''
            }
          }
        })
        // }
        response.data.selectFields.forEach(item => {
          if (item.businessType === 'number') {
            if (item.fieldsFormat === '0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 4,
                option: ''
              }
            } else if (item.fieldsFormat === '5') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 5,
                option: ''
              }
            } else if (item.fieldsFormat === '1k') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: 'abbreviate'
              }
            } else if (item.fieldsFormat === '%2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'percentage',
                decimals: 2,
                option: ''
              }
            }
            item.fieldsFormat = null
          } else if (item.businessType === 'currency') {
            if (item.fieldsFormat === '-$0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '-$1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '-$2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '-$3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '-$4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 4,
                option: ''
              }
            } else if (item.fieldsFormat === '0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 4,
                option: ''
              }
            }
            item.businessType = 'number'
            item.fieldsFormat = null
          }
        })
      }
    }

    if (response.config.url.includes('web/reports/sys/query/')) {
      if (
        response.data &&
        response.data.code === 0 &&
        response.data.data &&
        response.data.data.datasetSetting &&
        response.data.data.datasetSetting.sql &&
        response.data.data.datasetSetting.sql.select &&
        response.data.data.datasetSetting.sql.select.length > 0
      ) {
        // response.data.data.datasetSetting.sql.select.forEach(item => {
        //   if (item.businessType === 'datetime' && !item.fieldsFormat) {
        //     item.fieldsFormat = 'YYYY-MM-DD HH:mm'
        //   } else if (item.businessType === 'date' && !item.fieldsFormat) {
        //     item.fieldsFormat = 'YYYY-MM-DD'
        //   }
        // })
      }
      if (
        response.data &&
        response.data.code === 0 &&
        response.data.data &&
        response.data.data.measures &&
        response.data.data.measures.length > 0
      ) {
        // if (response.data.data.measures && response.data.data.measures.length > 0) {
        response.data.data.measures.forEach(item => {
          // if (item.businessType === 'datetime' && !item.fieldsFormat) {
          //   item.fieldsFormat = 'YYYY-MM-DD HH:mm'
          // } else if (item.businessType === 'date' && !item.fieldsFormat) {
          //   item.fieldsFormat = 'YYYY-MM-DD'
          // }
          if (
            item.businessType === 'number' &&
            !item.fieldsFormat &&
            !item.fieldsNewFormat
          ) {
            item.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 0,
              option: ''
            }
          }
        })
        // }
        response.data.data.measures.forEach(item => {
          if (item.businessType === 'number') {
            if (item.fieldsFormat === '0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 4,
                option: ''
              }
            } else if (item.fieldsFormat === '5') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 5,
                option: ''
              }
            } else if (item.fieldsFormat === '1k') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: 'abbreviate'
              }
            } else if (item.fieldsFormat === '%2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'percentage',
                decimals: 2,
                option: ''
              }
            }
            item.fieldsFormat = null
          } else if (item.businessType === 'currency') {
            if (item.fieldsFormat === '-$0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '-$1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '-$2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '-$3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '-$4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 4,
                option: ''
              }
            } else if (item.fieldsFormat === '0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 4,
                option: ''
              }
            }
            item.businessType = 'number'
            item.fieldsFormat = null
          }
        })
      }
      if (
        response.data &&
        response.data.code === 0 &&
        response.data.data &&
        response.data.data.dimensions &&
        response.data.data.dimensions.length > 0
      ) {
        // if (response.data.data.dimensions.length > 0) {
        response.data.data.dimensions.forEach(item => {
          // if (item.businessType === 'datetime' && !item.fieldsFormat) {
          //   item.fieldsFormat = 'YYYY-MM-DD HH:mm'
          // } else if (item.businessType === 'date' && !item.fieldsFormat) {
          //   item.fieldsFormat = 'YYYY-MM-DD'
          // }
          if (
            item.businessType === 'number' &&
            !item.fieldsFormat &&
            !item.fieldsNewFormat
          ) {
            item.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 0,
              option: ''
            }
          }
        })
        // }
        response.data.data.dimensions.forEach(item => {
          if (item.businessType === 'number') {
            if (item.fieldsFormat === '0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 4,
                option: ''
              }
            } else if (item.fieldsFormat === '5') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 5,
                option: ''
              }
            } else if (item.fieldsFormat === '1k') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: 'abbreviate'
              }
            } else if (item.fieldsFormat === '%2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'percentage',
                decimals: 2,
                option: ''
              }
            }
            item.fieldsFormat = null
          } else if (item.businessType === 'currency') {
            if (item.fieldsFormat === '-$0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '-$1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '-$2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '-$3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '-$4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'currency',
                decimals: 4,
                option: ''
              }
            } else if (item.fieldsFormat === '0') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 0,
                option: ''
              }
            } else if (item.fieldsFormat === '1') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 1,
                option: ''
              }
            } else if (item.fieldsFormat === '2') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 2,
                option: ''
              }
            } else if (item.fieldsFormat === '3') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 3,
                option: ''
              }
            } else if (item.fieldsFormat === '4') {
              item.fieldsNewFormat = {
                fieldsNewFormatType: 'number',
                decimals: 4,
                option: ''
              }
            }
            item.businessType = 'number'
            item.fieldsFormat = null
          }
        })
      }
      if (
        response.data &&
        response.data.code === 0 &&
        response.data.data &&
        response.data.data.calExpr
      ) {
        if (
          response.data.data.calExpr.businessType === 'number' &&
          !response.data.data.calExpr.fieldsFormat &&
          !response.data.data.calExpr.fieldsNewFormat
        ) {
          response.data.data.calExpr.fieldsNewFormat = {
            fieldsNewFormatType: 'number',
            decimals: 0,
            option: ''
          }
        }
        if (response.data.data.calExpr.businessType === 'number') {
          if (response.data.data.calExpr.fieldsFormat === '0') {
            response.data.data.calExpr.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 0,
              option: ''
            }
          } else if (response.data.data.calExpr.fieldsFormat === '1') {
            response.data.data.calExpr.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 1,
              option: ''
            }
          } else if (response.data.data.calExpr.fieldsFormat === '2') {
            response.data.data.calExpr.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 2,
              option: ''
            }
          } else if (response.data.data.calExpr.fieldsFormat === '3') {
            response.data.data.calExpr.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 3,
              option: ''
            }
          } else if (response.data.data.calExpr.fieldsFormat === '4') {
            response.data.data.calExpr.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 4,
              option: ''
            }
          } else if (response.data.data.calExpr.fieldsFormat === '5') {
            response.data.data.calExpr.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 5,
              option: ''
            }
          } else if (response.data.data.calExpr.fieldsFormat === '1k') {
            response.data.data.calExpr.fieldsNewFormat = {
              fieldsNewFormatType: 'number',
              decimals: 0,
              option: 'abbreviate'
            }
          } else if (response.data.data.calExpr.fieldsFormat === '%2') {
            response.data.data.calExpr.fieldsNewFormat = {
              fieldsNewFormatType: 'percentage',
              decimals: 2,
              option: ''
            }
          }
          response.data.data.calExpr.fieldsFormat = null
        }
      }
    }
  } catch (error) {}
  try {
    if (response.config.url === 'web/reports/tenant/app/install') {
    }
  } catch (error) {}
  try {
    if (response.config.url === '/web/um/sys/user/info') {
      if (response.data.code === 500) {
        if (response.data.msg.includes('tenant not find')) {
          clearLoginInfo()
          router.replace({
            name: 'login'
          })
        }
      }
    }
  } catch (error) {}

  return response
}

const successRequestHook = (config, response) => {
  let { url, data, params } = cloneDeep(response).config
  try {
    data = JSON.parse(data)
  } catch (error) {
    data = {}
  }

  if (
    url === 'web/reports/sys/model/sql' ||
    url === 'web/notice/tenant/task/filterlist'
  ) {
    InterceptContext.widgets = {
      ...InterceptContext.widgets,
      [data.gadgetId]: {
        url,
        data,
        params,
        res: response.data
      }
    }
  }
  if (
    /^\/web\/bots\/sys\/bot\/(\w+)\/switch$/.test(url) ||
    /^\/web\/bots\/tenant\/script\/switch$/.test(url)
  ) {
    if (response.data.code === 418 || response.data.code === 523) {
      InterceptContext.bot = {
        url,
        data,
        params,
        res: response.data
      }
    }
  }
}

const transform = {
  requestInterceptors,
  responseInterceptors,
  successRequestHook
}

const http = createAxios({ transform })

var postError = params => {
  apiInterface.um
    .postErrorAPI(params)
    .then(() => {})
    .catch(() => {})
}

export default http


const getQueryString = (name, search) => {
  search =
    search ||
    window.location.search.substr(1) ||
    window.location.hash.split('?')[1]
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  let r = search.match(reg)
  if (r != null) return unescape(r[2])
  return null
}
